define ['fizz', 'view/BootstrapView', 'knockback', 'knockout', 'model/Login' ],  (fizz, BootstrapView, kb, ko, Login) ->
  class LoginView extends BootstrapView
  
    # Events.
    events: {
      'submit form': 'submit'
    }

    # Render the template.
    renderTemplate: () ->
      $.get 'rest/logout'
      @mediator.publish 'login', ''
      @mediator.publish 'message', 'info', 'login.notice'
      @model = new Login()
      super()
      @bindModel()
        
    # bind the model.
    bindModel: () ->
      if _.isObject @viewModel
        @viewModel.destroy
      @viewModel = kb.viewModel @model
      ko.applyBindings @viewModel, @$el[0]
      
    submit: (e) ->
      unless @model.save {}, {
        success: (args...) => @success(args...),
        error: (args...) => @error(args...)
      }
        @error @model.validationError
        
    success: (data) ->
      @mediator.publish 'message', 'clear'
      @remove()
      @mediator.publish 'login', data
      fizz.utils.navigate '/'
      @mediator.subscribeOnce 'view:render:end', () =>
        @mediator.publish 'message', 'info', 'login.loginSuccess', @model.get 'login'

    error: (errors) ->
      @mediator.publish 'message', 'clear'
      if _.isArray(errors)
        _.each errors, (error) =>
          if _.isString(error)
            @mediator.publish 'message', 'error', error
          else if _.isObject(error)
            @mediator.publish 'message', 'error', error.message
      else
        @mediator.publish 'message', 'error', 'login.loginError'
      